import React, { useState, useCallback, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { TournamentState, TournamentConfig, RoundConfig } from '../types.ts';
import Wheel from '../components/Wheel.tsx';
import NameModal from '../components/NameModal.tsx';
import { UsersIcon } from '../components/icons/UsersIcon.tsx';
import * as api from '../utils/api.ts';

const CaptainDrawPage: React.FC = () => {
  const navigate = useNavigate();
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isNameModalOpen, setIsNameModalOpen] = useState(false);
  const [isSpinning, setIsSpinning] = useState(false);
  const [spinResult, setSpinResult] = useState<string | null>(null);
  const [drawResult, setDrawResult] = useState<any>(null);
  const [isResultModalOpen, setIsResultModalOpen] = useState(false);

  useEffect(() => {
    loadTournamentStatus();
    // 每5秒刷新一次状态
    const interval = setInterval(loadTournamentStatus, 5000);
    return () => clearInterval(interval);
  }, []);

  const loadTournamentStatus = async () => {
    try {
      const [statusResponse, configResponse] = await Promise.all([
        api.getTournamentStatus(),
        api.getTournamentConfig()
      ]);

      if (statusResponse.success && statusResponse.tournament_state) {
        setTournamentState(statusResponse.tournament_state);
      }

      if (configResponse.success && configResponse.config) {
        setTournamentConfig(configResponse.config);
      }

      setError(null);
    } catch (err) {
      setError('加载比赛状态失败');
      console.error('加载比赛状态失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDrawClick = useCallback(() => {
    if (isSpinning || loading) return;

    if (!tournamentState?.draw_enabled) {
      setError('当前不允许抽签，请等待管理员开启');
      return;
    }

    // 确保页面在顶部
    window.scrollTo(0, 0);
    setError(null);
    setIsNameModalOpen(true);
  }, [isSpinning, loading, tournamentState]);

  const handleNameSubmit = useCallback(async (name: string) => {
    const trimmedName = name.trim();
    if (!trimmedName) {
      setError('请输入队长姓名');
      return;
    }

    setIsNameModalOpen(false);
    setError(null);

    try {
      // 调用队长抽签接口
      const response = await api.draw({ name: trimmedName });

      if (response.success && response.result) {
        // 确保页面在顶部并设置转盘转动
        window.scrollTo(0, 0);
        
        // 根据抽签阶段设置转盘结果
        let wheelResult = '';
        const wheelGroups = getWheelGroups();

        if (response.result.group) {
          wheelResult = response.result.group;
        } else if (response.result.opponent) {
          // 对于对手匹配，随机选择一个转盘组别进行动画
          wheelResult = wheelGroups[Math.floor(Math.random() * wheelGroups.length)];
        } else if (response.result.bye) {
          // 对于轮空，随机选择一个转盘组别进行动画
          wheelResult = wheelGroups[Math.floor(Math.random() * wheelGroups.length)];
        } else {
          // 默认情况，随机选择一个转盘组别进行动画
          wheelResult = wheelGroups[Math.floor(Math.random() * wheelGroups.length)];
        }
        
        setSpinResult(wheelResult);
        setIsSpinning(true);

        // 等待转盘动画完成后显示结果
        setTimeout(() => {
          setIsSpinning(false);
          setDrawResult(response.result);
          setIsResultModalOpen(true);
          // 重新加载状态
          loadTournamentStatus();
        }, 4000); // 转盘动画持续4秒
      } else {
        setError(response.error || '抽签失败，请重试');
      }
    } catch (err) {
      setError('抽签失败，请重试');
      console.error('抽签失败:', err);
    }
  }, []);

  const getRoundDisplayName = (round: string): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round; // 如果找不到配置，返回原始名称
  };

  const getWheelGroups = (): string[] => {
    if (!tournamentState?.draw_stage || !tournamentConfig?.rounds) {
      return ['A', 'B', 'C', 'D', 'E'];
    }

    const stage = tournamentState.draw_stage;
    const roundConfig = tournamentConfig.rounds.find(r => r.name === stage);

    if (roundConfig) {
      // 根据轮次配置生成组别，使用字母编号
      const groupsCount = roundConfig.groups_count;
      return Array.from({ length: groupsCount }, (_, i) => String.fromCharCode(65 + i)); // A, B, C, D, E...
    } else {
      // 其他阶段显示对手或结果
      return ['A', 'B', 'C', 'D', 'E'];
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  if (!tournamentState) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-center">
          <div className="text-white text-xl mb-4">比赛尚未开始</div>
          <div className="text-white/70 text-sm">请等待管理员开启比赛</div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-4xl mx-auto">
        {/* 标题 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl md:text-4xl font-bold text-white">
            储能工厂羽毛球大赛
          </h1>
        </div>

        {/* 当前状态显示 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 mb-8 text-center">
          <h2 className="text-xl font-bold text-white mb-4">
            当前阶段: {getRoundDisplayName(tournamentState.current_round)}
          </h2>
          
          {tournamentState.current_round === 'final' ? (
            <div className="text-yellow-300 font-semibold">
              🏆 决赛已自动配对，无需抽签
            </div>
          ) : tournamentState.draw_enabled ? (
            <div className="space-y-2">
              <div className="text-green-300 font-semibold">
                ✓ {getRoundDisplayName(tournamentState.draw_stage)}抽签进行中
              </div>
              <div className="text-blue-200">
                已抽签: {tournamentState.drawn_captains?.length || 0} 人
              </div>
            </div>
          ) : (
            <div className="text-red-300 font-semibold">
              ⏸ 抽签暂停中，请等待管理员开启
            </div>
          )}
        </div>

        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded-lg mb-6 text-center">
            {error}
          </div>
        )}

        {/* 转盘区域或决赛信息 */}
        <div className="flex flex-col items-center space-y-8">
          {tournamentState.current_round === 'final' ? (
            // 决赛显示比赛信息
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-8 text-center max-w-md w-full">
              <h3 className="text-2xl font-bold text-yellow-300 mb-6">🏆 决赛对阵</h3>
              {(() => {
                const finalMatch = tournamentState.matches?.find(m => m.round === 'final');
                if (finalMatch) {
                  return (
                    <div className="space-y-4">
                      <div className="bg-blue-600/20 rounded-lg p-4">
                        <div className="text-lg font-semibold text-white">{finalMatch.team1.name}</div>
                        <div className="text-sm text-blue-200">队长: {finalMatch.team1.captain}</div>
                      </div>
                      <div className="text-2xl text-yellow-300 font-bold">VS</div>
                      <div className="bg-red-600/20 rounded-lg p-4">
                        <div className="text-lg font-semibold text-white">{finalMatch.team2.name}</div>
                        <div className="text-sm text-red-200">队长: {finalMatch.team2.captain}</div>
                      </div>
                      {finalMatch.completed ? (
                        <div className="mt-4 p-4 bg-green-600/20 rounded-lg">
                          <div className="text-green-300 font-semibold">比赛已完成</div>
                          <div className="text-white">获胜者: {finalMatch.winner?.name}</div>
                        </div>
                      ) : (
                        <div className="mt-4 text-yellow-200">比赛进行中...</div>
                      )}
                    </div>
                  );
                } else {
                  return <div className="text-white">决赛信息加载中...</div>;
                }
              })()}
            </div>
          ) : (
            // 其他轮次显示转盘和抽签按钮
            <>
              <Wheel
                groups={getWheelGroups()}
                isSpinning={isSpinning}
                result={spinResult}
              />

              <button
                onClick={handleDrawClick}
                disabled={isSpinning || !tournamentState.draw_enabled}
                className={`
                  relative px-8 py-4 rounded-full font-bold text-xl transition-all duration-300 transform
                  ${isSpinning || !tournamentState.draw_enabled
                    ? 'bg-gray-600 text-gray-300 cursor-not-allowed'
                    : 'bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 hover:scale-105 shadow-lg hover:shadow-xl'
                  }
                `}
              >
                {isSpinning ? '抽签中...' :
                 !tournamentState.draw_enabled ? '等待开启' :
                 '开始抽签'}
              </button>
            </>
          )}

          {/* 分组情况快捷按钮 */}
          <div className="mt-6">
            <Link
              to="/groups"
              className="flex items-center gap-3 px-6 py-3 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 text-white hover:bg-white/20 hover:border-white/30 transition-all duration-300 shadow-lg hover:shadow-xl"
            >
              <UsersIcon className="w-5 h-5" />
              <span className="font-medium">查看分组情况</span>
            </Link>
          </div>
        </div>

        {/* 模态框 */}
        <NameModal
          isOpen={isNameModalOpen}
          onClose={() => setIsNameModalOpen(false)}
          onSubmit={handleNameSubmit}
          error={error}
        />

        {/* 结果模态框 */}
        {isResultModalOpen && drawResult && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl p-6 max-w-md w-full text-center">
              <h3 className="text-2xl font-bold text-gray-800 mb-4">抽签结果</h3>
              
              {drawResult.group && (
                <div className="space-y-2">
                  <div className="text-lg text-gray-600">分配到</div>
                  <div className="text-3xl font-bold text-blue-600">{drawResult.group} 组</div>
                </div>
              )}
              
              {drawResult.opponent && (
                <div className="space-y-2">
                  <div className="text-lg text-gray-600">对手是</div>
                  <div className="text-3xl font-bold text-red-600">{drawResult.opponent.name}</div>
                  <div className="text-sm text-gray-500">队长: {drawResult.opponent.captain}</div>
                </div>
              )}
              
              {drawResult.bye && (
                <div className="space-y-2">
                  <div className="text-lg text-gray-600">恭喜！</div>
                  <div className="text-3xl font-bold text-green-600">轮空直接复活</div>
                </div>
              )}
              
              <button
                onClick={() => setIsResultModalOpen(false)}
                className="mt-6 bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg"
              >
                确定
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default CaptainDrawPage;
